﻿using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using DefektaiApp.Properties;
using ewal.Msg;
using ewal.Data;

namespace DefektaiApp
{
    public enum RequestScenario { text_textbox, integer_textbox, integer_combobox };
    public abstract partial class fTvarkytiItems : Form
    {
        protected BindingSource bindingSource = new BindingSource();
        protected OleDbDataAdapter dAdapter;
        protected OleDbCommandBuilder cBuilder;
        protected DataTable dTable = new DataTable();
        protected DataView dView = new DataView();
        protected bool hasChanges = false;

        public fTvarkytiItems(string formTitle, string sqlSelectStatement)
        {
            InitializeComponent();
            this.Text = formTitle;
            this.dAdapter = new OleDbDataAdapter(sqlSelectStatement, Settings.Default.DbConnectionString);
            cBuilder = new OleDbCommandBuilder(dAdapter);
            buildInsertUpdateCommands();
        }

        protected void fTvarkytiItems_Load(object sender, EventArgs e)
        {
            query();
            foreach (DataGridViewColumn column in dgvItems.Columns)
                { column.DataPropertyName = column.Name; }            
            dgvItems.AutoResizeColumns();
            doColumns();
            tsbSave.Enabled = false;
            tsbDelete.Enabled = false;
            this.dgvItems.SelectionChanged += new System.EventHandler(this.dgvItems_SelectionChanged);
        }

        protected void query()
        {
            dTable.Clear();
            dAdapter.Fill(dTable);
            dView = dTable.DefaultView;
            bindingSource.DataSource = dView;
            dgvItems.DataSource = bindingSource;
        }

        protected void tsbSave_Click(object sender, EventArgs e)
        {
            endEditAndSave();
        }

        protected void dgvItems_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            Msg.WarningMsg(Messages.Netinka_reiksme);
            return;
        }

        protected void dgvItems_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            hasChanges = true;
            tsbSave.Enabled = true;
        }

        protected void endEditAndSave()
        {
            dgvItems.EndEdit(DataGridViewDataErrorContexts.Commit);
            bindingSource.EndEdit();
            dAdapter.Update(dTable);
            hasChanges = false;
            tsbSave.Enabled = false;
        }

        protected void deleteRecord(ArrayList sqlsCheckIfInUse, string sqlDelete)
        {
            int id = Convert.ToInt32(dgvItems.SelectedRows[0].Cells["id"].Value);
			foreach (string sqlSt in sqlsCheckIfInUse)
			{
				if (DbHelper.FetchSingleValue(string.Format(sqlSt, id)) != null)
				{
					Msg.ExclamationMsg(Messages.Naudojamas_negalima_istrinti);
					return;
				}
			}
			
			// Paskutinį kartą patikslinama, ar tikrai ištrinti
            if (Msg.YesNoQuestion(Messages.Ar_tikrai_istrinti) == DialogResult.No)
            {
                return;
            }
            DbHelper.ExecuteNonQuery(string.Format(sqlDelete, id));

            query();
		}

        protected void deleteRecord(string sqlCheckIfInUse, string sqlDelete)
        {
            int id = Convert.ToInt32(dgvItems.SelectedRows[0].Cells["id"].Value);

            // turi nebūti įrašų su šituo objektu - nei aktų, nei vadovų,  nei suvirintojų

            if (DbHelper.FetchSingleValue(string.Format(sqlCheckIfInUse, id)) != null)
                {
                    Msg.ExclamationMsg(Messages.Naudojamas_negalima_istrinti);
                    return;
                }
            

            // Paskutinį kartą patikslinama, ar tikrai ištrinti
            if (Msg.YesNoQuestion(Messages.Ar_tikrai_istrinti) == DialogResult.No)
            {
                return;
            }
            DbHelper.ExecuteNonQuery(string.Format(sqlDelete, id));

            query();
        }

        protected DialogResult requestData(RequestScenario scenario,
            string[] texts)
        {
            // texts[0] - requestFormCaption
            // texts[1] - requestLabelText
            // texts[2] - comboboxValuesSql
            using (fRequest requestForm = new fRequest(scenario, texts))
            {
                requestForm.ShowDialog();
                return requestForm.DialogResult;
            }
        }

        protected void doThings(string sqlFindDupl, string sqlInsert)
			{
				if (DbHelper.FetchSingleValue(sqlFindDupl) != null)
				{
					Msg.ExclamationMsg(Messages.Objektas_jau_yra);
					return;
				}
				
				try
				{
					DbHelper.ExecuteNonQuery(sqlInsert);
				}
				catch
				{
                    Msg.ErrorMsg(Messages.DbErrorMsg);
					return;
				}
				query();
				Msg.InformationMsg(Messages.Irasas_sukurtas);			
			}

        protected void doThings(string sqlInsertWithoutParam)
        {
            string padalinioIdString;
            if (Program.pubInt == -1)
            {
                return;
            }
            else if (Program.pubInt == 0)
            {
                padalinioIdString = "Null";
            }
            else
            {
                padalinioIdString = Program.pubInt.ToString();
            }

            try
            {
                DbHelper.ExecuteNonQuery(string.Format(sqlInsertWithoutParam, padalinioIdString));
            }
            catch
            {
                Msg.ErrorMsg(Messages.DbErrorMsg);
                return;
            }
            query();
            Msg.InformationMsg(Messages.Irasas_sukurtas);
        }

        protected void tsbExit_Click(object sender, EventArgs e)
        {
            if (hasChanges)
            {
                DialogResult result = Msg.YesNoCancelQuestion(Messages.Yra_neissaugotu_ar_issaugoti);

                if (result == DialogResult.No)  // pakeitimų yra, bet neišsaugoti
                {
                    Close();
                }
                else if (result == DialogResult.Cancel) // pakeitimų yra, bet nutraukti veiksmą
                {
                    return;
                }
                else   // pakeitimų yra ir išsaugoti
                {
                    endEditAndSave();
                    Close();
                }
            }
            else // pakeitimų nėra - išeiti ir viskas
            {
                Close();
            }
        }

        protected void dgvItems_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvItems.CurrentRow != null && dgvItems.Rows[dgvItems.CurrentRow.Index].Selected == true)
            {
                tsbDelete.Enabled = true;
            }
            else
            {
                tsbDelete.Enabled = false;
            }
        }

        protected virtual void buildInsertUpdateCommands()
        {
            // intentionally left blank
            // may be overrident in descendants
        }

        protected virtual void doColumns()
        {
            //dgvItems.Columns["Inv_Nr"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        protected virtual void tsbDelete_Click(object sender, EventArgs e)
        {
            //// eilutė turi būti pažymėta
            //if (dgvItems.SelectedRows.Count != 1)
            //{
            //    MessageBox.Show(Messages.Jeigu_norite_istrinti);
            //    return;
            //}

            //int id = Convert.ToInt32(dgvItems.SelectedRows[0].Cells["id"].Value);

            //// turi nebūti įrašų su šituo objektu
            //string sqlSt = "SELECT id FROM Aktai WHERE tikrin_defektoskopasId={0};";
            //if (DbHelper.fetchSingleValue(string.Format(sqlSt, id)) != null)
            //{
            //    MessageBox.Show(Messages.Naudojamas_negalima_istrinti);
            //    return;
            //}

            //// Paskutinį kartą patikslinama, ar tikrai ištrinti
            //if (MessageBox.Show(Messages.Ar_tikrai_istrinti,
            //    "Patikslinimas",
            //    MessageBoxButtons.YesNo,
            //    MessageBoxIcon.Question,
            //    MessageBoxDefaultButton.Button2) == DialogResult.No)
            //{
            //    return;
            //}

            //sqlSt = "DELETE FROM Defektoskopai WHERE id={0};";
            //DbHelper.executeNonQuery(string.Format(sqlSt, id));

            //query();
        }

        protected virtual void tsbNew_Click(object sender, EventArgs e)
        {
            //using (fRequestInt dfskopCodeRequestForm = new fRequestInt(
            //    "Defektoskopas",
            //    "Įveskite naują defektoskopo kodą:"))
            //{
            //    dfskopCodeRequestForm.ShowDialog();
            //    if (dfskopCodeRequestForm.DialogResult == DialogResult.Cancel)
            //        return;
            //}

            //// patikrinti, ar geras kodas

            //// 1. turi būti >0           
            //if (Program.pubInt < 0) return; 

            
            //string sqlCheckSt = "SELECT id FROM Defektoskopai WHERE id={0};";
            //string sqlInsertSt = "INSERT INTO Defektoskopai (id, isActive) VALUES ({0}, {1});";
            //doThings(sqlSt, sqlSt);
        }        

    }
}
